package org.jim.server.demo.config;

import org.jim.server.demo.common.interceptor.Interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;


@Configuration
public class WebConfig implements WebMvcConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebConfig.class);

    @Value("${file.path}")
    public String filePath;

    @Resource
    private Interceptor interceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        /**
         * 访问的URL路径
         */
        registry.addResourceHandler("/upload/**")
                /**
                 * 静态资源文件的存储位置
                 */
                .addResourceLocations("file:" + filePath);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("注册自定义拦截器!!!!");
        registry.addInterceptor(interceptor)
                .addPathPatterns("*") // 拦截所有路径
                .excludePathPatterns("/api/v1/auht/mobile/code",
                        "/api/v1/auht/mobile/login",
                        "/upload",
                        "/api/v1/test",
                        "/filetransfer/**"); // 放行特定路径
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 明确指定允许的来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 包括 OPTIONS 方法
                .allowedHeaders("*") // 允许所有自定义头
                .allowCredentials(false); // 如果需要支持 cookie 或其他凭证
    }

}
